package io.sage.modules.employer.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import io.sage.common.utils.R;
import io.sage.common.validator.ValidatorUtils;
import io.sage.modules.employer.entity.Employer;
import io.sage.modules.employer.service.EmployerService;
import io.sage.modules.sys.entity.SysDeptEntity;
import io.sage.modules.sys.entity.SysUserEntity;
import io.sage.modules.sys.service.SysDeptService;
import io.sage.modules.sys.shiro.ShiroUtils;
import io.swagger.annotations.ApiOperation;
/**
 * @author xujh
 * @email jhang_mail@163.com
 * @date 2018-07-09 13:48:15
 */
@RestController
@RequestMapping("student/student")
public class EmployerController {
	@Autowired
	private EmployerService studentService;

	@Autowired
	private SysDeptService deptService;
	/**
	 * 列表
	 */
//    @RequestMapping("/list")
//    @RequiresPermissions("student:student:list")
//    @DataFilter(tableAlias="e", subDept = true, user = true )
//    public R list(@RequestParam Map<String, Object> params){
//        PageUtils selectStudentList = studentService.selectStudentList(params);
//        return R.ok().put("page", selectStudentList);
//    }

	@ResponseBody
	@GetMapping("/list")
	public R list(@RequestParam Map<String, Object> params) {
		Integer pageSize = 1;
		if (params != null && params.get("limit") != null) {
			pageSize = java.lang.Integer.parseInt(params.get("limit").toString());
		}
		Integer pageNum = 10;
		if (params != null && params.get("page") != null) {
			pageNum = java.lang.Integer.parseInt(params.get("page").toString());
		}

		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		System.out.println(params.get("examinationName"));
		if(params.get("examinationName")!=null){

			if(!"".equals(params.get("examinationName").toString())){
				paramMap.put("examinationName", params.get("examinationName").toString());
			}
		}

		if(params.get("studentName")!=null){
			if(!"".equals(params.get("studentName").toString())){
				paramMap.put("studentName", params.get("studentName").toString());
			}
		}

		if(params.get("deptNo")!=null){
			if(!"".equals(params.get("deptNo").toString())){
				paramMap.put("deptNumber", params.get("deptNo").toString());
			}
		}

		PageHelper.startPage(pageNum, pageSize);// 设置分页的起始码以及页面大小

		List<Employer> scoreListVo = studentService.selectStudentLists(paramMap);

		PageInfo<Employer> pageInfo = new PageInfo<Employer>(scoreListVo);// 传入list就可以了

		return R.ok().put("selectStudentList", pageInfo);
	}


	/**
	 * 信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("student:student:info")
	public R info(@PathVariable("id") Integer id){

		Employer student = studentService.selectByPrimaryKey(id);
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("studentId", id);

		Map<String, Object> returnMap  = new HashMap<String, Object>();
		returnMap.put("student", student);

		return R.ok().put("map", returnMap);
	}

	/**
	 * 密码重置.
	 */
	@RequestMapping("/reset")
	@RequiresPermissions("student:student:reset")
	public R Reset(@RequestBody Integer id){

		int reset = studentService.reset(id);
		if(reset>0){
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 保存
	 */
	@RequestMapping("/save")
	@RequiresPermissions("student:student:save")
	public R save(@RequestBody JSONObject jsonObject){
		Employer student = jsonObject.getObject("student", Employer.class);

		Employer selectByUserName = studentService.selectByUserName(student.getUserName());
		if(selectByUserName!=null){
			return R.error("用户名已经存在");
		}
		
		Integer employeeDeptId = student.getEmployeeDeptId();

		SysDeptEntity dept = deptService.selectById(employeeDeptId);

		SysUserEntity user = ShiroUtils.getUserEntity();
		student.setDeptId(dept.getDeptId().intValue());
		student.setDeptNumber(dept.getDeptNo());
		int insert = studentService.insert(student,user);

		if(insert>0){
			return R.ok();
		}

		return R.error();
	}

	/**
	 * 修改
	 */
	@RequestMapping("/update")
	@RequiresPermissions("student:student:update")
	public R update(@RequestBody JSONObject jsonObject){
		Employer student = jsonObject.getObject("student", Employer.class);

		ValidatorUtils.validateEntity(student);

		SysDeptEntity dept = deptService.selectById(student.getEmployeeDeptId());
		student.setDeptNumber(dept.getDeptNo());


		int update = studentService.updateByPrimaryKeySelective(student);//全部更新

		if(update>0){
			return R.ok();
		}
		return R.error();
	}

	/**
	 * 批量删除.
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("student:student:delete")
	public R delete(@RequestBody Integer[] ids){

		int delete = studentService.deleteBatchIds(ids);

		if(delete>0){
			return R.ok();
		}

		return R.error();
	}
	/**
	 * 批量导入.
	 */
	@PostMapping("/imports")
	@RequiresPermissions("student:student:import")
	public R importQuestions(MultipartFile file, String deptId, Integer majorRoleId, Integer useTimeTypeCode){

		if(StringUtils.isEmpty(deptId)|| "undefined".equals(deptId)){
			return R.error("部门id不允许为空!");
		}
		SysUserEntity user = ShiroUtils.getUserEntity();

		SysDeptEntity dept = deptService.getDeptById(Long.parseLong(deptId));

		Map<String, Object> importQuestions = studentService.importStudents(file, Integer.parseInt(deptId),user, dept, majorRoleId, useTimeTypeCode);

		return R.ok(importQuestions);
	}

	@RequestMapping(value = "/download")
	@RequiresPermissions("student:student:download")
	public void localFileDownload(HttpServletResponse response,HttpServletRequest request) {
		InputStream fis = null;
		OutputStream os = null;
		String fileName = "导入学员表.xls";
		String filePath =  EmployerController.class.getResource("/templates/temp/导入学员表.xls").getPath();;
		try {
			filePath = URLDecoder.decode(filePath, "UTF-8");
			File file = new File(filePath);
			if(!file.exists()){
				return;
			}
			if (!StringUtils.hasText(fileName)) {
				fileName = file.getName();
			}
			fis = new BufferedInputStream(new FileInputStream(filePath));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			response.reset();

			if (request.getHeader("User-Agent").indexOf("Chrome") > 1) {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
			} else if ((request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0)
					|| (request.getHeader("User-Agent").indexOf("like Gecko") >0)) {
				fileName = URLEncoder.encode(fileName, "UTF-8");
				fileName = fileName.replaceAll("\\+",  "%20"); //处理空格
			} else {
				fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
				fileName = "\"" + fileName + "\""; //处理空格
			}

			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Content-Length", String.valueOf(file.length()));
			os = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			os.write(buffer);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}



	/**
	 * 更新状态是否启用.
	 */
	@RequestMapping(value = "/updateState" , method = RequestMethod.POST)
	@RequiresPermissions("student:student:updateState")
	@ApiOperation("试题类型停用/启用")
	public R updateState(@RequestBody Employer student){

		int updateState = studentService.updateByState(student);//全部更新
		if(updateState>0){

			return R.ok();

		}
		return R.error();
	}

}
